package com.minhua.jijiehao2.view;

import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.minhua.jijiehao2.R;
import com.minhua.jijiehao2.base.adapter.ViewHolder;

/**
 * @author moo
 * @date 2017/12/12.
 * @describe
 */

public class CustomDialog extends Dialog {
    private ViewHolder mViewHolder;

    public CustomDialog(@NonNull Context context, int resId) {
        this(context, resId, true);
    }

    public CustomDialog(@NonNull Context context, int resId, boolean hasBack) {
        this(context, resId, hasBack, Gravity.CENTER);
    }

    public CustomDialog(@NonNull Context context, int resId, boolean hasBack, int gravity) {
        super(context);
        initView(resId, hasBack, gravity);
    }


    private void initView(int resId, boolean hasBack, int gravity) {
        mViewHolder = ViewHolder.get(getContext(), null, null, resId, 0);
        if (hasBack) {
            try {
                mViewHolder.setOnClickListener(R.id.tvDismiss, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismiss();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        getWindow().setGravity(gravity);
        getWindow().setBackgroundDrawable(new ColorDrawable(0));
        if (gravity == Gravity.BOTTOM) {
            setContentView(mViewHolder.getConvertView(), new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
            getWindow().getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            getWindow().setAttributes(lp);
        } else {
            setContentView(mViewHolder.getConvertView(), new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        }
        setCanceledOnTouchOutside(false);
    }

    public ViewHolder getViewHolder() {
        return mViewHolder;
    }
}
